<template>
  <el-dialog :title="titleName" :visible="showDialog" @close="btnCancel">
    <el-form
      ref="rulesForm"
      :model="formData"
      :rules="rules"
      status-icon
      label-width="120px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :eows="5"
        /> </el-form-item></el-form>
    <el-row type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel"> 取消 </el-button>
        <el-button
          size="small"
          type="primary"
          @click="adddepts"
        >确定</el-button>
      </el-col>
      <el-row type="flex" justify="center">
        <el-col>
          <el-button size="small" @click="resetForm('rulesForm')">
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartDetail,
  updateDepartments
} from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    // 当前节点信息
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    // 检查部门名称是否相同
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      console.log(depts)
      let deptsName = null
      if (this.formData.id) {
        // 有id则为编辑部门
        deptsName = depts
          .filter(
            (item) =>
              item.pid === this.treeNode.pid && item.id !== this.treeNode.id
          )
          .some((item) => item.name === value)
      } else {
        // 无id则为添加部门
        deptsName = depts
          .filter((item) => item.pid === this.treeNode.id)
          .some((item) => item.name === value)
      }
      deptsName ? callback(new Error(`同级部门下已经存在${value}`)) : callback()
    }
    // 检查编码是否相同
    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let codeDepts
      let codeName = null
      if (this.formData.id) {
        // 有id为编辑部门
        codeDepts = depts.some(
          (item) => item.id !== this.treeNode.id && item.code === value
        )
      } else {
        codeDepts = depts.some((item) => item.code === value)
      }
      codeName = depts.filter((item) => item.code === value)[0]?.name
      codeDepts
        ? callback(new Error(`当前${codeName}的部门编码为${value}`))
        : callback()
    }
    return {
      peoples: [], // 部门负责人
      dialogVisible: true,
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 500,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符'
          }
        ]
      }
    }
  },
  computed: {
    // 直接当做普通属性调用不加括号
    // 任何data中数据变化立即重新计算
    // 计算属性会缓存
    titleName() {
      return this.formData.id ? '编辑部门' : '添加子部门'
    }
  },
  methods: {
    // 点击取消按钮
    btnCancel() {
      setTimeout(() => {
        this.formData = {
          name: '', // 部门名称
          code: '', // 部门编码
          manager: '', // 部门管理者
          introduce: '' // 部门介绍
        }
        this.$refs.rulesForm.resetFields()
      }, 500)
      this.$emit('update:showDialog', false)
    },
    resetForm(val) {
      this.$refs[val].resetFields()
    },
    // 获取部门负责人列表
    async getEmployeeSimple() {
      this.peoples = await getEmployeeSimple()
    },
    // 点击确定验证表单添加部门
    adddepts() {
      this.$refs.rulesForm.validate(async(isOk) => {
        if (isOk) {
          if (this.formData.id) {
            // 编辑部门
            // 编辑模式  调用编辑接口
            await updateDepartments(this.formData)
            this.$message.success('编辑成功')
          } else {
            // 添加部门
            await addDepartments({ ...this.formData, pid: this.treeNode.id })
            this.$message.success('添加成功')
          }
          this.$emit('addDepts')
          this.$emit('update:showDialog', false)
        }
      })
    },
    // 点击编辑部门后获取当前节点的信息
    async getDepartDetail(id) {
      this.formData = await getDepartDetail(id)
    }
  }
}
</script>

<style></style>
